package com.orangelife.mobile.parkingcard.activity;

import android.annotation.TargetApi;
import android.app.ActivityManager;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.ComponentName;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.OrangeHttpBiz;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.net.NetworkUtil;
import com.curry.android.util.JSONHelper;
import com.curry.android.util.ScreenUtil;
import com.curry.orangelife.mobile.R;
import com.google.gson.reflect.TypeToken;
import com.orangelife.mobile.common.activity.OrangeLifeBaseActivity;
import com.orangelife.mobile.parkingcard.bean.ParkingListBean;
import com.orangelife.mobile.util.LogE;
import com.orangelife.mobile.parkingcard.bean.ParkingInfomation;
import com.orangelife.mobile.parkingcard.biz.ParkingCardHttpBiz;
import com.orangelife.mobile.parkingcard.fragment.NoDataFragment;
import com.orangelife.mobile.parkingcard.fragment.PrivateFragment;
import com.orangelife.mobile.parkingcard.fragment.PublicFragment;
import com.orangelife.mobile.parkingcard.widget.ParkingTitlePopupWindow;
import com.orangelife.mobile.shop.biz.Trader;
import com.orangelife.mobile.util.BLog;
import com.orangelife.mobile.util.ToastHelper;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 停车位列表
 * Created by yyx on 2015/11/17.
 * <p/>
 * 代码结构极其错误与混乱（不同接口混在一起写，数据存在静态变量中等等），
 * 但是牵涉太多，暂无时间修改，只做稍微修整，以提高可读性
 *
 * @author yyx
 */
public class ParkingCardListActivity extends OrangeLifeBaseActivity {

    private static final int WHAT_PRIVATE = 1;
    @Bind(R.id.ib_title_left)
    LinearLayout ibTitleLeft;
    @Bind(R.id.tv_all_classfication)
    TextView tvAllClassfication;
    @Bind(R.id.flContent)
    FrameLayout flContent;
    @Bind(R.id.dividerTop)
    View dividerTop;
    @Bind(R.id.llTop)
    LinearLayout llTop;

    /**
     * 1表示私有，2表示公有
     */
    private int type = 1;

    private NoDataFragment noDataFragment;
    private PrivateFragment privateFragment;
    private PublicFragment publicFragment;
    private Fragment currentFragment;

    /**
     * 下拉弹出框
     */
    public ParkingTitlePopupWindow popCondition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_parking_card_list);
        ButterKnife.bind(this);
        findView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestList();
        BLog.getInstance().intAppmod(BLog.PARKCARD);
    }

    /***
     * 初始化和赋值
     */
    private void findView() {
        tvAllClassfication.setText("私有车位");
    }

    boolean isDestroyed = false;

    /**
     * 请求私人已认证的车位
     */
//    private void requestHasCertParkingSpace() {
//        showDialog(this);
//        ParkingCardHttpBiz.getHasCertParkingSpace(new VolleyHttpUtil.ResponseCallBack() {
//            @Override
//            public void handleResponse(JSONObject response, int errCode) {
//                closeDialog();
//                if (isActivityHasDestroyed()) {
//                    return;
//                }
//                if (OrangeErrorHandler.getInstance().isSuccess(response)) {
//                    Map<String, Object> map = JSONHelper
//                            .jsonToMap(String.valueOf(response));
//                    Map<String, Object> entity = (Map<String, Object>) map.get("entity");
//                    if (entity != null && entity.containsKey("usedParkingSpaces") && entity.containsKey("totalParkingSpaces")) {
//                        List<Map<String, Object>> usedVehicleList = (List<Map<String, Object>>) entity.get("usedVehicle");
//                        List<Map<String, Object>> totalVehicleList = (List<Map<String, Object>>) entity.get("totalVehicle");
//                        int usedParkingSpaces = Integer.parseInt(entity.get("usedParkingSpaces").toString());
//                        int totalParkingSpaces = Integer.parseInt(entity.get("totalParkingSpaces").toString());
//                        String ownerID = String.valueOf(entity.get("ownerID"));
//                        showPrivateFragment(usedVehicleList, totalVehicleList, usedParkingSpaces, totalParkingSpaces, ownerID);
//                    } else {
//                        showEmptyFragment();
//                    }
//                } else if (errCode == 73004) {
//                    showEmptyFragment();
//                }
//            }
//        });
//    }
    private boolean isActivityHasDestroyed() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            isDestroyed = isDestroyed();
        }
        if (isDestroyed || !isRunningForeground(ParkingCardListActivity.this)) {
            LogE.E(ParkingCardListActivity.class.getSimpleName(), "The activity has been destroyed,stop requesting");
            return true;
        }
        return false;
    }

    private void requestList() {
        if (type == 1) {
            showDialog(this);
            ParkingCardHttpBiz.getHasCertParkingSpace1(handler, WHAT_PRIVATE);
        } else {
            showDialog(this);
            requestParkingCardList();
        }
    }

    private void requestParkingCardList() {
//        showDialog(this);
        ParkingCardHttpBiz.getParkingCardList(null, null, new VolleyHttpUtil.ResponseCallBack() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
            @Override
            public void handleResponse(JSONObject response, int errCode) {
                closeDialog();
                if (isActivityHasDestroyed()) {
                    return;
                }
                if (OrangeErrorHandler.getInstance().isSuccess(response)) {
                    Map<String, Object> jsonMap = JSONHelper
                            .jsonToMap(String.valueOf(response));
                    if (jsonMap != null) {
                        JSONHelper
                                .jsonToMap(String.valueOf(response));
                        List<Map<String, Object>> list = (List<Map<String, Object>>) jsonMap.get("pageEntity");
                        if (list != null && list.size() > 0) {
                            showPublicParkingFragment(list);
                        } else {
                            showEmptyFragment();
                        }
                    } else {
                        showEmptyFragment();
                    }
                } else if (errCode == 73004) {
                    showEmptyFragment();
                }
            }
        });
    }

    /**
     * 没有数据的Fragment
     */
    private void showEmptyFragment() {
        ParkingInfomation.setType(type);
        if (noDataFragment == null) {
            noDataFragment = new NoDataFragment();
        }
        if (currentFragment == noDataFragment) {
            noDataFragment.updateUI();
        } else {
            getFragmentManager().beginTransaction().replace(R.id.flContent, noDataFragment).commitAllowingStateLoss();
            currentFragment = noDataFragment;
        }
    }

    private void showPublicParkingFragment(List<Map<String, Object>> list) {
        setPublicFragmentData(list);
        if (publicFragment == null) {
            publicFragment = new PublicFragment();
        }
        if (currentFragment == publicFragment) {
            publicFragment.updateUI();
        } else {
            getFragmentManager().beginTransaction().replace(R.id.flContent, publicFragment).commitAllowingStateLoss();
            currentFragment = publicFragment;
        }
    }

    /**
     * 私有车位的第一次的Fragment
     */
    private void showPrivateFragment() {
        if (privateFragment == null) {
            privateFragment = new PrivateFragment();
        }
        if (currentFragment == privateFragment) {
            privateFragment.updateUI();
        } else {
            getFragmentManager().beginTransaction().replace(R.id.flContent, privateFragment).commitAllowingStateLoss();
            currentFragment = privateFragment;
        }

    }

    private void setPrivateFragmentData(List<Map<String, Object>> list, List<Map<String, Object>> list2, int usedParkingSpaces, int totalParkingSpaces, String ownerID) {
        ParkingInfomation.setListUsed(list);
        ParkingInfomation.setListTotal(list2);
        ParkingInfomation.setOwnerID(ownerID);
        ParkingInfomation.setUsedParkingSpaces(usedParkingSpaces);
        ParkingInfomation.setTotalParkingSpaces(totalParkingSpaces);
    }

    private void setPublicFragmentData(List<Map<String, Object>> list) {
        ParkingInfomation.setListPublic(list);
    }

    @OnClick(R.id.llTop)
    public void onClick(View view) {
        if (popCondition != null) {
            popCondition.dismiss();
        }
        showCondition();
    }

    /**
     * 判断activity是否在前台运行
     *
     * @param context
     * @return
     */
    private boolean isRunningForeground(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if (!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(getPackageName())) {
            return true;
        }
        return false;
    }

    private void showCondition() {
        popCondition = new ParkingTitlePopupWindow(this);
        popCondition.setText(tvAllClassfication);
        popCondition.setOnPopupWindowClickListener(new ParkingTitlePopupWindow.OnPopupWindowItemClickListener() {
            @Override
            public void onPopupWindowItemClick(int clickPositon,
                                               String strItemData) {
                popCondition.dismiss();
                if (!NetworkUtil.isConnectedNet(ParkingCardListActivity.this)) {
                    Toast.makeText(
                            ParkingCardListActivity.this,
                            getResources().getString(
                                    R.string.net_disconnected),
                            Toast.LENGTH_SHORT).show();
                    return;
                }
                /* 保存点击项并将值赋值给标题 */
                Trader.getInstance().setSpConditionPosition(
                        clickPositon);
                if (strItemData.equals(getResources()
                        .getString(R.string.private_parking))) {
                    type = 1;
                } else if (strItemData.equals(getResources()
                        .getString(R.string.pulbic_parking))) {
                    type = 2;
                }
                tvAllClassfication.setText(strItemData);
                requestList();
            }
        });
//        int px = -(popCondition.getWidth() - tvAllClassfication.getWidth()) / 2;
//        int py = tvAllClassfication.getHeight();
        popCondition.showAtLocation(dividerTop, Gravity.TOP, ScreenUtil.dip2px(this, 10), ScreenUtil.dip2px(this, 75));
//        popCondition.showAsDropDown(v);
    }


    private android.os.Handler handler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case WHAT_PRIVATE:
                    closeDialog();
                    JSONObject response = null;
                    try {
                        response = new JSONObject(String.valueOf(msg.obj));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    if (response == null) {
                        return;
                    }
                    int errCode = ((JSONObject) response).optInt("errCode", -1);
                    String strErrCode = String.valueOf(errCode);
                    if (isActivityHasDestroyed()) {
                        return;
                    }
                    /*是否未认证*/
                    boolean hasCert = true;
                    boolean isOk = false;
                    if (OrangeErrorHandler.getInstance().isSuccess(response)) {
                        Map<String, Object> map = JSONHelper
                                .jsonToMap(String.valueOf(response));

                        Map<String, Object> entity = (Map<String, Object>) map.get("entity");
                        if (entity != null && entity.containsKey("usedParkingSpaces") && entity.containsKey("totalParkingSpaces")) {
                            List<Map<String, Object>> usedVehicleList = (List<Map<String, Object>>) entity.get("usedVehicle");
                            List<Map<String, Object>> totalVehicleList = (List<Map<String, Object>>) entity.get("totalVehicle");
                            int usedParkingSpaces = Integer.parseInt(entity.get("usedParkingSpaces").toString());
                            int totalParkingSpaces = Integer.parseInt(entity.get("totalParkingSpaces").toString());
                            String ownerID = String.valueOf(entity.get("ownerID"));
                            setPrivateFragmentData(usedVehicleList, totalVehicleList, usedParkingSpaces, totalParkingSpaces, ownerID);
                            isOk = true;
                        }
                    } else if (strErrCode.equals("73004")) {
                        hasCert = false;
                    }

                    if (hasCert) {//else if (strErrCode.equals("73004"))
                        if (!isOk) {
                            setPrivateFragmentData(null, null, 0, 0, null);
                        }
                        showPrivateFragment();
                    } else {
                        showEmptyFragment();
                    }

                    break;
//                case 500:
//                    ToastHelper.getInstance()._toast(String.valueOf(msg.obj));
//                    closeDialog();
//                    break;
                default:
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isDestroyed = true;
        BLog.getInstance().intAppmod(BLog.PARKCARD);
    }


}
